import axios from 'axios'
import { axiosConfig } from './config'

const api = axios.create(axiosConfig)

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 如果是登录请求，添加特殊处理
    if (config.url === '/api/token') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      delete config.headers['Accept']
    }
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    console.log('API Response:', response)  // 添加日志
    // 直接返回响应数据
    return response.data
  },
  error => {
    console.error('API Error:', error.response || error)  // 添加错误日志
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default api 